pub mod technical;
pub mod ml;
pub mod monitoring;
pub mod indicators;
pub mod memory;
pub mod parallel;

use serde::{Deserialize, Serialize};
use chrono::{DateTime, Utc};

use self::{
    technical::{MarketAnalysis, TechnicalAnalyzer, IndicatorConfig},
    ml::{MarketPredictor, MLModelConfig, MarketPrediction},
    monitoring::{MarketMonitor, BacktestResult},
    indicators::AdvancedIndicatorCalculator,
};

/// 高级市场分析器配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AdvancedMarketAnalyzerConfig {
    /// 技术指标配置
    pub indicator_config: Option<IndicatorConfig>,
    /// 机器学习模型配置
    pub ml_config: Option<MLModelConfig>,
    /// 监控配置
    pub monitoring_config: Option<MonitoringConfig>,
}

/// 监控配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MonitoringConfig {
    /// 警报阈值
    pub alert_thresholds: AlertThresholds,
    /// 回测配置
    pub backtest_config: BacktestConfig,
}

/// 警报阈值配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertThresholds {
    /// 价格变化阈值
    pub price_change_threshold: f64,
    /// 波动率阈值
    pub volatility_threshold: f64,
    /// 成交量阈值
    pub volume_threshold: f64,
}

/// 回测配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BacktestConfig {
    /// 初始资金
    pub initial_capital: f64,
    /// 手续费率
    pub fee_rate: f64,
    /// 止损比例
    pub stop_loss_ratio: f64,
    /// 止盈比例
    pub take_profit_ratio: f64,
}

impl Default for AdvancedMarketAnalyzerConfig {
    fn default() -> Self {
        Self {
            indicator_config: Some(IndicatorConfig::default()),
            ml_config: Some(MLModelConfig::default()),
            monitoring_config: Some(MonitoringConfig {
                alert_thresholds: AlertThresholds {
                    price_change_threshold: 0.02, // 2%
                    volatility_threshold: 0.03,   // 3%
                    volume_threshold: 2.0,        // 2倍于平均成交量
                },
                backtest_config: BacktestConfig {
                    initial_capital: 100000.0,
                    fee_rate: 0.001,       // 0.1%
                    stop_loss_ratio: 0.02,  // 2%
                    take_profit_ratio: 0.05, // 5%
                },
            }),
        }
    }
}

/// 高级市场分析器
pub struct AdvancedMarketAnalyzer {
    /// 技术分析器
    technical_analyzer: TechnicalAnalyzer,
    /// 机器学习预测器
    predictor: MarketPredictor,
    /// 市场监控器
    monitor: MarketMonitor,
    /// 高级指标计算器
    advanced_indicator_calculator: AdvancedIndicatorCalculator,
    /// 配置
    config: AdvancedMarketAnalyzerConfig,
}

/// 高级市场分析结果
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AdvancedMarketAnalysis {
    /// 基础市场分析
    pub base_analysis: MarketAnalysis,
    /// 市场预测
    pub prediction: MarketPrediction,
    /// 高级技术指标
    pub advanced_indicators: AdvancedIndicators,
    /// 回测结果
    pub backtest_results: Option<BacktestResult>,
}

/// 高级技术指标
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AdvancedIndicators {
    /// 趋势强度指数
    pub trend_strength_index: f64,
    /// 市场效率系数
    pub market_efficiency_ratio: f64,
    /// 价格动量指标
    pub price_momentum: f64,
    /// 波动率预测
    pub volatility_forecast: f64,
    /// 市场微观结构指标
    pub microstructure_indicators: MicrostructureIndicators,
}

/// 市场微观结构指标
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MicrostructureIndicators {
    /// 买卖压力比率
    pub buy_sell_pressure_ratio: f64,
    /// 流动性指标
    pub liquidity_index: f64,
    /// 市场深度
    pub market_depth: f64,
    /// 价格影响
    pub price_impact: f64,
}

impl AdvancedMarketAnalyzer {
    /// 创建新的高级市场分析器
    pub fn new(config: Option<AdvancedMarketAnalyzerConfig>) -> Self {
        let config = config.unwrap_or_default();
        
        Self {
            technical_analyzer: TechnicalAnalyzer::new(config.indicator_config.clone()),
            predictor: MarketPredictor::new(config.ml_config.clone()),
            monitor: MarketMonitor::new(),
            advanced_indicator_calculator: AdvancedIndicatorCalculator::new(20),
            config,
        }
    }

    /// 分析市场
    pub fn analyze_market(
        &mut self,
        prices: &[(f64, f64, f64, f64)], // (open, high, low, close)
        volumes: &[f64],
        timestamp: DateTime<Utc>,
    ) -> AdvancedMarketAnalysis {
        // 提取价格数据
        let close_prices: Vec<f64> = prices.iter().map(|&(_, _, _, c)| c).collect();
        let high_prices: Vec<f64> = prices.iter().map(|&(_, h, _, _)| h).collect();
        let low_prices: Vec<f64> = prices.iter().map(|&(_, _, l, _)| l).collect();

        // 计算技术指标
        let indicators = self.technical_analyzer.calculate_indicators(prices, volumes);

        // 计算高级技术指标
        let advanced_indicators = self.advanced_indicator_calculator.calculate_indicators(
            &close_prices,
            &high_prices,
            &low_prices,
            volumes,
        );

        // 基础市场分析
        let base_analysis = self.analyze_base_market(&indicators, &close_prices, volumes, &high_prices, &low_prices);

        // 市场预测
        let prediction = self.predictor.predict(&indicators, &base_analysis, &close_prices, volumes);

        // 更新市场监控
        self.monitor.update(
            timestamp,
            close_prices.last().unwrap_or(&0.0).clone(),
            volumes.last().unwrap_or(&0.0).clone(),
            base_analysis.clone(),
            Some(prediction.clone()),
        );

        // 构建高级分析结果
        AdvancedMarketAnalysis {
            base_analysis,
            prediction,
            advanced_indicators: self.calculate_advanced_indicators(
                &indicators,
                &advanced_indicators,
                &close_prices,
                volumes,
            ),
            backtest_results: None,
        }
    }

    /// 运行回测
    pub fn run_backtest(
        &mut self,
        start_time: DateTime<Utc>,
        end_time: DateTime<Utc>,
    ) -> BacktestResult {
        let config = self.config.monitoring_config.as_ref().unwrap();
        self.monitor.run_backtest(
            start_time,
            end_time,
            config.backtest_config.initial_capital,
        )
    }

    /// 分析基础市场状态
    fn analyze_base_market(
        &mut self,
        indicators: &technical::IndicatorResult,
        prices: &[f64],
        volumes: &[f64],
        high_prices: &[f64],
        low_prices: &[f64],
    ) -> MarketAnalysis {
        let mut analyzer = technical::MarketStateAnalyzer::new();
        analyzer.analyze_market(indicators, prices, volumes, high_prices, low_prices)
    }

    /// 计算高级指标
    fn calculate_advanced_indicators(
        &self,
        indicators: &technical::IndicatorResult,
        advanced_indicators: &indicators::AdvancedIndicatorResult,
        prices: &[f64],
        volumes: &[f64],
    ) -> AdvancedIndicators {
        // 计算趋势强度指数
        let trend_strength_index = if let Some(&tsi) = advanced_indicators.tsi.last() {
            tsi
        } else {
            0.0
        };

        // 计算市场效率系数
        let market_efficiency_ratio = self.calculate_market_efficiency(prices);

        // 计算价格动量
        let price_momentum = if let Some(&cmo) = advanced_indicators.cmo.last() {
            cmo
        } else {
            0.0
        };

        // 计算波动率预测
        let volatility_forecast = self.calculate_volatility_forecast(prices);

        // 计算市场微观结构指标
        let microstructure_indicators = self.calculate_microstructure_indicators(prices, volumes);

        AdvancedIndicators {
            trend_strength_index,
            market_efficiency_ratio,
            price_momentum,
            volatility_forecast,
            microstructure_indicators,
        }
    }

    /// 计算市场效率系数
    fn calculate_market_efficiency(&self, prices: &[f64]) -> f64 {
        if prices.len() < 2 {
            return 0.0;
        }

        let price_change = (prices.last().unwrap() - prices.first().unwrap()).abs();
        let path_length: f64 = prices.windows(2)
            .map(|w| (w[1] - w[0]).abs())
            .sum();

        if path_length == 0.0 {
            0.0
        } else {
            price_change / path_length
        }
    }

    /// 计算波动率预测
    fn calculate_volatility_forecast(&self, prices: &[f64]) -> f64 {
        if prices.len() < 20 {
            return 0.0;
        }

        // 使用GARCH(1,1)模型的简化版本
        let returns: Vec<f64> = prices.windows(2)
            .map(|w| (w[1] - w[0]) / w[0])
            .collect();

        let mut variance = returns.iter()
            .map(|&r| r * r)
            .sum::<f64>() / returns.len() as f64;

        // 使用EWMA方法更新波动率预测
        let alpha = 0.94;
        for &ret in returns.iter().rev().take(5) {
            variance = alpha * variance + (1.0 - alpha) * ret * ret;
        }

        variance.sqrt()
    }

    /// 计算市场微观结构指标
    fn calculate_microstructure_indicators(&self, prices: &[f64], volumes: &[f64]) -> MicrostructureIndicators {
        let buy_sell_pressure_ratio = self.calculate_buy_sell_pressure(prices, volumes);
        let liquidity_index = self.calculate_liquidity_index(volumes);
        let market_depth = self.calculate_market_depth(prices, volumes);
        let price_impact = self.calculate_price_impact(prices, volumes);

        MicrostructureIndicators {
            buy_sell_pressure_ratio,
            liquidity_index,
            market_depth,
            price_impact,
        }
    }

    /// 计算买卖压力比率
    fn calculate_buy_sell_pressure(&self, prices: &[f64], volumes: &[f64]) -> f64 {
        if prices.len() < 2 || prices.len() != volumes.len() {
            return 1.0;
        }

        let mut buy_volume = 0.0;
        let mut sell_volume = 0.0;

        for i in 1..prices.len() {
            if prices[i] > prices[i - 1] {
                buy_volume += volumes[i];
            } else if prices[i] < prices[i - 1] {
                sell_volume += volumes[i];
            }
        }

        if sell_volume == 0.0 {
            2.0 // 表示极强的买入压力
        } else {
            buy_volume / sell_volume
        }
    }

    /// 计算流动性指标
    fn calculate_liquidity_index(&self, volumes: &[f64]) -> f64 {
        if volumes.is_empty() {
            return 0.0;
        }

        let avg_volume = volumes.iter().sum::<f64>() / volumes.len() as f64;
        let std_dev = (volumes.iter()
            .map(|&v| (v - avg_volume).powi(2))
            .sum::<f64>() / volumes.len() as f64)
            .sqrt();

        avg_volume / (std_dev + 1.0) // 添加1.0避免除以零
    }

    /// 计算市场深度
    fn calculate_market_depth(&self, prices: &[f64], volumes: &[f64]) -> f64 {
        if prices.len() < 2 || prices.len() != volumes.len() {
            return 0.0;
        }

        let price_changes: Vec<f64> = prices.windows(2)
            .map(|w| (w[1] - w[0]).abs())
            .collect();

        let volume_price_ratio: Vec<f64> = volumes.iter()
            .zip(price_changes.iter())
            .map(|(&v, &p)| if p != 0.0 { v / p } else { v })
            .collect();

        volume_price_ratio.iter().sum::<f64>() / volume_price_ratio.len() as f64
    }

    /// 计算价格影响
    fn calculate_price_impact(&self, prices: &[f64], volumes: &[f64]) -> f64 {
        if prices.len() < 2 || prices.len() != volumes.len() {
            return 0.0;
        }

        let price_changes: Vec<f64> = prices.windows(2)
            .map(|w| (w[1] - w[0]).abs() / w[0])
            .collect();

        let weighted_impact: f64 = price_changes.iter()
            .zip(volumes.iter())
            .map(|(&p, &v)| p * v)
            .sum();

        let total_volume: f64 = volumes.iter().sum();

        if total_volume > 0.0 {
            weighted_impact / total_volume
        } else {
            0.0
        }
    }
}